/*
 * @Author: yanjikun
 * @Date: 2022-05-20 17:39:20
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-16 10:37:22
 * @Description: file content
 */

import { PROJECT_CONFIG } from '@/enums/cacheEnums'
import { storage } from '@/utils/Storage'
import { ConfigProvider } from 'ant-design-vue'
import { Theme } from 'ant-design-vue/es/config-provider'
import { defineStore } from 'pinia'
import logo from '@/assets/logo.png'
import { ref } from 'vue'
import { supervisionConfigByDomain } from '@/api/global'

export type ProjectState = {
  primaryColor: string
  basicInfo: Omit<API.SupervisionConfigInfoResult, 'id' | 'orgName'>
  fullScreen: boolean
}

export type { Theme }
const defaultConfig: ProjectState = {
  primaryColor: '#1890ff',
  basicInfo: {
    domainName: 'http://localhost:3000',
    shortName: '项目模板',
    platform: '基于Vue3中后台项目模板',
    slogan: '',
    technicalSupport: '©Copyright 2022 技术支持:后台项目模板',
    icp: '蜀ICP备2021032286号-1',
    logo: logo,
  },
  fullScreen: false,
}
let localThemeConfig: Partial<ProjectState> = {}
try {
  localThemeConfig = storage.get(PROJECT_CONFIG, {})
  const { primaryColor } = localThemeConfig
  primaryColor &&
    ConfigProvider.config({
      theme: {
        primaryColor,
      },
    })
} catch (error) {
  localThemeConfig = {}
}
export const useProjectStore = defineStore({
  id: 'project',
  state: (): ProjectState => ({
    ...defaultConfig,
    ...localThemeConfig,
  }),
  getters: {
    getBasicInfo() {
      return () => this.basicInfo
    },
  },
  actions: {
    setConfig(config: Partial<ProjectState>) {
      for (const key in config) {
        this[key] = config[key]
      }
      storage.set(PROJECT_CONFIG, this.$state)
    },
    fillColor(theme: Theme) {
      this.primaryColor = theme.primaryColor ?? this.primaryColor
      ConfigProvider.config({
        theme,
      })
      storage.set(PROJECT_CONFIG, this.$state)
    },
    initBasicInfo() {
      const loading = ref(true)
      this.basicInfo = {
        domainName: '',
        shortName: '',
        platform: '',
        slogan: '',
        technicalSupport: '',
        icp: '',
        logo: logo,
      }
      supervisionConfigByDomain({
        domain: location.origin,
      })
        .then((data) => {
          if (!data.domainName) {
            this.setConfig({ basicInfo: defaultConfig.basicInfo })
            return
          }
          this.setConfig({
            basicInfo: { ...data, logo: data.logo ? `${location.origin}/${data.logo}` : logo },
          })
        })
        .catch(() => {
          this.setConfig({ basicInfo: defaultConfig.basicInfo })
        })
        .finally(() => {
          loading.value = false
        })
      return loading
    },
  },
})
